//
//  PhotoAlbumHelper.m
//  WeCommunity
//
//  Created by mac on 2017/6/19.
//  Copyright © 2017年 lzy. All rights reserved.
//

#import "PhotoAlbumHelper.h"
#import "CheckAPPSetting.h"
#import "PhotoAlbumModel.h"

static PhotoAlbumHelper * photoAlbumHelper = nil;

typedef NS_ENUM(NSUInteger, ImagePickerControllerFilterType) {
    ImagePickerControllerFilterTypeNone,
    ImagePickerControllerFilterTypePhotos,
    ImagePickerControllerFilterTypeVideos
};

ALAssetsFilter * ALAssetsFilterFromImagePickerControllerFilterType(ImagePickerControllerFilterType type) {
    switch (type) {
        case ImagePickerControllerFilterTypeNone:
            return [ALAssetsFilter allAssets];
            break;
            
        case ImagePickerControllerFilterTypePhotos:
            return [ALAssetsFilter allPhotos];
            break;
            
        case ImagePickerControllerFilterTypeVideos:
            return [ALAssetsFilter allVideos];
            break;
    }
}

@interface PhotoAlbumHelper ()
{
    NSInteger _count;
    NSInteger _customIndex;
}

@property (nonatomic,strong) ALAssetsLibrary * library;

@property (nonatomic,strong) ALAssetsGroup * assetsGroup;
@property (nonatomic,strong) NSMutableArray * assetGroups;
@property (nonatomic,strong) NSMutableArray * albumArray;



@end

@implementation PhotoAlbumHelper

+(PhotoAlbumHelper *)shared
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        photoAlbumHelper = [[PhotoAlbumHelper alloc] init];
        
        //ALAssetsLibrary 此对象被销毁后 下文获取到的ALAsset对象将失效
        photoAlbumHelper.library = [[ALAssetsLibrary alloc] init];
    });
    return photoAlbumHelper;
}


#pragma mark - 获取所有照片
-(void)reloadingAllPicturesAndComplete:(void(^)(BOOL success,NSArray *results))doneBlock
{
    [CheckAPPSetting checkPhotos:^(bool isAuthorized) {
        if (isAuthorized) {
            
            self.assetGroups = [[NSMutableArray alloc] init];
            self.albumArray = [NSMutableArray array];
            _customIndex = 0;
            
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
                
//                void (^assetEnumerator)( ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
//                    if(result != nil) {
//                        NSLog(@"%@==%ld",result,index);
//                        [self.albumArray addObject:result];
////                        if([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) {
////                            if (_count == index + 1) {
////                                dispatch_async(dispatch_get_main_queue(), ^{
////                                    doneBlock(YES,self.albumArray,index);
////                                });
////                            }else{
//                                [self.albumArray addObject:result];
////                            }
////                        }
//                    }
//                };
                
                //相册分组
                void (^ assetGroupEnumerator) ( ALAssetsGroup *, BOOL *)= ^(ALAssetsGroup *group, BOOL *stop) {
                    if(group != nil) {
                        
                        NSString* groupType = [group valueForProperty:ALAssetsGroupPropertyType];
                        if ([groupType integerValue] == 16) { //所有照片
                            self.assetsGroup = group;
                            _count = [self.assetsGroup numberOfAssets];
//                            [self.assetsGroup enumerateAssetsUsingBlock:assetEnumerator];
                            //加载当前分组下所有照片
                            [self loadAllAssetsForGroups];
                            dispatch_async(dispatch_get_main_queue(), ^{
                                doneBlock(YES,self.albumArray);
                            });
                        }
                        [self.assetGroups addObject:group];
                    }
                };
                
                [self.library enumerateGroupsWithTypes:ALAssetsGroupAll
                 
                                        usingBlock:assetGroupEnumerator
                 
                                      failureBlock:^(NSError *error) {
                                          NSLog(@"There is an error");
                                      }];
                
                
                
            });
        }else
        {
            doneBlock(NO,nil);
        }
    }];
}

- (void)loadAllAssetsForGroups
{
    [self.assetsGroup setAssetsFilter:ALAssetsFilterFromImagePickerControllerFilterType(ImagePickerControllerFilterTypePhotos)];
    
    // Load assets
    __block NSUInteger numberOfAssets = 0;
    __block NSUInteger numberOfPhotos = 0;
    __block NSUInteger numberOfVideos = 0;
    
    [self.assetsGroup enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
        if (result) {
            numberOfAssets++;
            NSString *type = [result valueForProperty:ALAssetPropertyType];
            if ([type isEqualToString:ALAssetTypePhoto]){
                numberOfPhotos++;
                [self.albumArray addObject:result];
            }else if ([type isEqualToString:ALAssetTypeVideo]){
                numberOfVideos++;
            }
        }
    }];
}


#pragma mark - 保存图片到相册
-(void)saveImage:(UIImage*)image
         toAlbum:(NSString*)albumName
 completionBlock:(SaveImageCompletion)completionBlock
{
    __weak PhotoAlbumHelper *weakSelf = self;
    [self.library writeImageToSavedPhotosAlbum:image.CGImage
                                         orientation:(ALAssetOrientation)image.imageOrientation
                                     completionBlock:^(NSURL *assetURL, NSError *error) {
                                         //error handling
                                         if (error) {
                                             completionBlock(nil, error);
                                             return;
                                         }
                                         
                                         //添加照片到某个分组
                                         PhotoAlbumHelper  *strongSelf = weakSelf;
                                         if (albumName.length > 0) {
                                             [strongSelf addAssetURL:assetURL
                                                             toAlbum:albumName
                                                     completionBlock:completionBlock];
                                         }else{
                                             [strongSelf.library assetForURL: assetURL
                                                                 resultBlock:^(ALAsset *asset) {
                                                                     completionBlock(asset,nil);
                                                                 } failureBlock:^(NSError *error) {
                                                                     completionBlock(nil,error);
                                                                 }];
                                         }
                                     }];
}

#pragma mark -添加照片到某个分组
-(void)addAssetURL:(NSURL*)assetURL
           toAlbum:(NSString*)albumName
   completionBlock:(SaveImageCompletion)completionBlock
{
    __weak PhotoAlbumHelper *weakSelf = self;
    __block BOOL albumWasFound = NO;
    
    [self.library enumerateGroupsWithTypes:ALAssetsGroupAll
                                      usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
                                          PhotoAlbumHelper  *strongSelf = weakSelf;
                                          //compare the names of the albums
                                          if ([albumName compare: [group valueForProperty:ALAssetsGroupPropertyName]]==NSOrderedSame) {
                                              
                                              //target album is found
                                              albumWasFound = YES;
                                              
                                              //get a hold of the photo's asset instance
                                              [strongSelf.library assetForURL: assetURL
                                                                        resultBlock:^(ALAsset *asset) {
                                                                            //add photo to the target album
                                                                            [group addAsset: asset];
                                                                            //run the completion block
                                                                            completionBlock(asset,nil);
                                                                            
                                                                        } failureBlock:^(NSError *error) {
                                                                            completionBlock(nil,error);
                                                                        }];
                                              
                                              //album was found, bail out of the method
                                              *stop = YES;
                                              return;
                                          }
                                          
                                          if (group==nil && albumWasFound==NO) {
                                              //photo albums are over, target album does not exist, thus create it
                                              //create new assets album
                                              
                                              __weak ALAssetsLibrary *weakLibray = strongSelf.library;
                                              
                                              [strongSelf.library addAssetsGroupAlbumWithName:albumName
                                                                                        resultBlock:^(ALAssetsGroup *group) {
                                                                                            //get the photo's instance
                                                                                            [weakLibray assetForURL:assetURL
                                                                                                        resultBlock:^(ALAsset *asset) {
                                                                                                            //add photo to the newly created album
                                                                                                            [group addAsset: asset];
                                                                                                            
                                                                                                            //call the completion block
                                                                                                            completionBlock(asset,nil);
                                                                                                        } failureBlock:^(NSError *error) {
                                                                                                            completionBlock(nil,error);
                                                                                                        }];
                                                                                            
                                                                                        } failureBlock:^(NSError *error) {
                                                                                            completionBlock(nil,error);
                                                                                        }];
                                              
                                              //should be the last iteration anyway, but just in case
                                              *stop = YES;
                                              return;
                                          }
                                          
                                      } failureBlock:^(NSError *error) {
                                          completionBlock(nil,error);
                                          
                                      }];
}


@end
